package repositories

import (
	"fmt"
	"gin-students-surrealdb/models"
	"github.com/surrealdb/surrealdb.go"
)

type StudentRepository struct {
	db *surrealdb.DB
}

func NewStudentRepository(db *surrealdb.DB) *StudentRepository {
	return &StudentRepository{db: db}
}

func (r *StudentRepository) Create(student *models.Student) (*models.Student, error) {
	// 使用 Create 方法
	var response []models.Student

	response, err := surrealdb.Create[models.Student{}](r.db, "students", student)

	if err != nil {
		return nil, fmt.Errorf("failed to create student: %w", err)
	}

	if len(response) == 0 {
		return nil, nil
	}

	return &response[0], nil
}

func (r *StudentRepository) GetAll() ([]models.Student, error) {
	var response []models.Student

	err := r.db.Send(
		&response,
		"select",
		"students", // 表名
	)

	if err != nil {
		"SELECT * FROM students",
		&response,
	)
}

func (r *StudentRepository) GetByID(id string) (*models.Student, error) {
	var response []models.Student

	err := r.db.Send(
		&response,
		"select",
		id, // 记录ID
	)

	if err != nil {
		"SELECT * FROM $id",
		map[string]interface{}{"id": id},
		&response,
	)
		return nil, fmt.Errorf("student not found")
	}

	return &response[0], nil
}

func (r *StudentRepository) Update(id string, student *models.Student) (*models.Student, error) {
	var response []models.Student

	err := r.db.Send(
		&response,
		"update",
		id,      // 记录ID
		student, // 更新数据
		"UPDATE $id SET name = $name, age = $age",
		map[string]interface{}{
			"id": id,
			"name": student.Name,
			"age": student.Age,
		},
		&response,
	)

	if len(response) == 0 {
		return nil, fmt.Errorf("empty response from database")
	}

	return &response[0], nil
}

func (r *StudentRepository) Delete(id string) error {
	var response interface{}

	err := r.db.Send(
		&response,
		"delete",
		id, // 记录ID
	)
		"DELETE FROM $id",
		map[string]interface{}{"id": id},
		&response,
	)